<?php
require_once '../funciones.php';
	$con = con_caweb();
    $proveedor=$_SESSION['caweb']['nit'];
    $factura=$_SESSION['caweb']['factura'];
    $fecIni =$_SESSION['caweb']['fecIni'];
    $fecFin =$_SESSION['caweb']['fecFin'];
    //Validacion de las fechas
    $fecIni = ($fecIni == "")?"1986-01-01":$fecIni;
    $fecFin = ($fecFin == "")?"2999-01-01":$fecFin;
    $condicion ="";
    $condicion .=($proveedor != "")?" AND a.proveedor='$proveedor'":"";
    $condicion .=($factura != "")?" AND a.factura='$factura' ":"";
    $condicion .= " and a.fechacompra between '$fecIni' and '$fecFin' ";
    $condicion2 ="";
    $condicion2 .=($proveedor != "")?" AND a.terceroref='$proveedor'":"";
    $condicion2 .=($factura != "")?" AND a.numeroref='$factura' ":"";
    $condicion2 .= " AND LEFT(b.item,1) IN ('P','R','A','S','H','L') AND b.interno = '' ";

	$page = $_REQUEST['page']; 

	// get how many rows we want to have into the grid - rowNum parameter in the grid 
	$limit = $_REQUEST['rows']; 

	// get index row - i.e. user click to sort. At first time sortname parameter -
	// after that the index from colModel 
	$sidx = $_REQUEST['sidx']; 
	
	// sorting order - at first time sortorder 
	$sord = $_REQUEST['sord']; 

	// if we not pass at first time index use the first column for the index or what you want
	if(!$sidx) $sidx =1; 

	// calculate the number of rows for the query. We need this for paging the result 
//	$result = mysql_query("SELECT COUNT(*) AS count FROM seriales WHERE 1=1 $condicion2 GROUP BY item "); 
//	$row = mysql_fetch_array($result,MYSQL_ASSOC); 
//	$count = $row['count']; 
	$count = 0;

	// calculate the total pages for the query 
	if( $count > 0 ) $total_pages = ceil($count/$limit); 
	else $total_pages = 0; 

	// if for some reasons the requested page is greater than the total 
	// set the requested page to total page 
	if ($page > $total_pages) $page=$total_pages;

	// calculate the starting position of the rows 
	$start = $limit*$page - $limit;

	// if for some reasons start position is negative set it to 0 
	// typical case is that the user type 0 for the requested page 
	if($start <0) $start = 0; 

	// the actual query for the grid data
	 
$SQL="(SELECT count(*) AS cantidad,a.item,a.modelo,b.taxDesc as descripcion,a.preciocompra,sum(preciocompra) AS valor,a.interno as llave,'s' as tabla,a.factura,pr.nombre as proveedor
FROM seriales AS a 
INNER JOIN intranetpccom.taxonomia AS b
ON b.codigotaxonomia = a.item
inner join proveedores pr on pr.nit = a.proveedor
WHERE a.preciocompra > 1 $condicion GROUP BY a.item,a.factura,a.proveedor)
UNION ALL
(SELECT count(*) AS cantidad,a.item,a.modelo,b.taxDesc AS descripcion,a.preciocompra,sum(preciocompra) AS valor,a.interno as llave,'sp' as tabla,a.factura,pr.nombre as proveedor
FROM seriales_partes AS a 
INNER JOIN intranetpccom.taxonomia AS b
ON b.codigotaxonomia = a.item
inner join proveedores pr on pr.nit = a.proveedor
WHERE a.preciocompra > 1 $condicion  GROUP BY a.item,a.factura,a.proveedor)
UNION ALL
(SELECT b.cantidad,b.item,'' AS modelo,d.taxDesc AS descripcion,b.preciocompra,(b.cantidad*b.preciocompra) AS valor,b.id as llave,'det' as tabla,a.numeroref as factura,pr.nombre as proveedor
FROM cabeceras AS a
inner join proveedores pr on pr.nit = a.terceroref
INNER JOIN detalles AS b ON a.transaccion = b.transaccion
inner join cabeceras_oc oc on oc.oc = a.numeroref1 and oc.fecha between '$fecIni' and '$fecFin'
INNER JOIN intranetpccom.taxonomia AS d ON d.codigotaxonomia = b.item
WHERE b.preciocompra > 1 and a.documento = 'ECO' $condicion2) ORDER BY $sidx $sord LIMIT $start , $limit";

$result = mysql_query($SQL,$con) or die("Error en seriales.".mysql_error().$SQL);
   
    
    // we should set the appropriate header information
	if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
				  header("Content-type: application/xhtml+xml;charset=utf-8"); 
	} else {
			  header("Content-type: text/xml;charset=utf-8");
	}
	echo "<?xml version='1.0' encoding='utf-8'?>";
	echo "<rows>";
//        echo "<sql>".$SQL."</sql>";
	echo "<page>".$page."</page>";
	echo "<total>".$total_pages."</total>";
	echo "<records>".$count."</records>";        
        $totaltotal=0;
	while($row = mysql_fetch_array($result)){
            $tmp = trim($row['llave'])."-pp-".trim($row['tabla'])."-pp-".trim($row['cantidad']);
		echo "<row id='".$tmp."'>"; //."$row['llave']-pp-".$row['tabla']
                $tmp =($row['descripcion'] =="")?$row['modelo']:$row['descripcion'];
		echo "<cell>". $row['cantidad']."</cell>";
                echo "<cell>". $row['factura']."</cell>";
		echo "<cell>". utf8_encode(htmlspecialchars($row['proveedor']))."</cell>";
                echo "<cell>". utf8_encode(htmlspecialchars($tmp))."</cell>";
		echo "<cell>". number_format($row['preciocompra'],2, ',', '.')."</cell>";
		echo "<cell>". number_format($row['valor'],2, ',', '.')."</cell>";
		echo "</row>";
                $totaltotal=$totaltotal+$row['valor'];
	}
        echo "<row>";
        echo "<cell> </cell><cell> </cell><cell> </cell>";
        echo "<cell> </cell>";
        echo "<cell> Total </cell>";
        echo "<cell>". number_format($totaltotal,2, ',', '.')."</cell>";
        echo "</row>";
	echo "</rows>"; 
?>
